<template>
	<view class="content">
		<!-- 建模中的动画 -->
		<view class="content content_bg">
			<view class="head"><text class="headT1">全脑健康模型建立中</text></view>
			<view class="perView">
				<text class="percentText">{{ percentText }}%</text>
				<progress :percent="percent" activeColor="#2AC2DB" active active-mode="forwards" stroke-width="15" border-radius="500" />
				<view class="content" style="margin-top: 50rpx;"><text class="destext">建模时 请保持安静状态</text></view>
			</view>
		</view>
		<annoyFree-popup ref="annoyPopup" :icon_src="icon_src" @btnEvent="btnEvent"></annoyFree-popup>
	</view>
</template>

<script>
const app = getApp();
import util from '../../../utils/utils.js';
import * as api from '@/api/login';

// 定义变量
var totaldata = new Array();
var bloodL = new Array(); //左脑血流数据（500个float长度）
var bloodR = new Array(); //右脑血流数据（500个float长度）

export default {
	data() {
		return {
			whereGo: null,  //建模结束自动跳转到哪个页面
			bloodCount: 0, //计数器  ..判断数组是否组合完成 血流
			maxsize: 8407, //数组的最大长度
			percent: 0, //进度
			percentText: 0, //进度文字
			Timer: 0, //定时器 ---进度
			delayTimer:null,
			icon_src:'',
			innerAudioContext: null,
			isOver:false,  //是否
			exceptionT:null, //处理异常的定时器
			exitCount:0, // 返回次数触发计数
			overlayCount:0, //叠加?
			overlayData:{L:[],R:[]}, //叠加的数据
		};
	},
	onLoad(option) {
		console.log('>>option>>' + typeof JSON.parse(option.whereGo));
		this.whereGo = JSON.parse(option.whereGo)
		plus.device.setWakelock(true);
		this.$toast('请您调整手机音量');
	},
	onReady() {
		// 定义一个音频
		this.innerAudioContext = uni.createInnerAudioContext();
		this.innerAudioContext.autoplay = false;
		this.innerAudioContext.loop = false;
		this.StartBuild()
	},
	onUnload() {
		totaldata = 0;
		bloodL = new Array();
		bloodR = new Array();
		uni.$off('originalData');
	},
	methods: {
		// 开始建模
		StartBuild() {
			let that = this;
			this.playAudio(this.$config.StaticUrl + "/audio/healthyModel/healthyModel.mp3");
			that.delayTimer = setTimeout(() => {
				app.writeBLEState(1);
				uni.$on('originalData', function(data) {
					let array = Array.prototype.slice.call(new Uint8Array(data.msg));
					that.DealMessage(array);
				});
				that.Timer = setInterval(() => {
					console.log(that.percent);
					if (that.percent > 98) {
						that.percent = 99;
						that.percentText = 99;
						clearInterval(that.Timer);
						that.exceptionT = setTimeout(() =>{
							if(!that.isOver) that.dealException();
							clearTimeout(that.exceptionT);
						},10000);
					}else {
						that.percent += 1;
						that.percentText += 1;
					}
				}, 1000);
				clearTimeout(that.delayTimer);
			}, 10000);
		},
		dealException(){
			let that = this;
			bloodL = new Array();
			bloodR = new Array();
			app.writeBLEState(2);
			let content={
				text1:"请您调整头环",
				text2:"保持安静",
				text3:"重新开始建模",
				btn_text:"再次建模"
			};
			that.icon_src = "../../../static/image/iconPopup/icon_quiet.png";
			that.$refs.annoyPopup.openPopup(content,'center');
			that.playAudio(that.$config.StaticUrl + "/audio/healthyModel/ajustBuild.mp3");
		},
		// 数据处理
		DealMessage(array) {
			// console.log('array>>>>',array);
			let that = this;
			if (array[0] === 0x68 && array[2] === 0x08 && array[3] === 0x06 && array[7] === 0x16) {
				let CrcContent = array.slice(1, 5);
				let crc16 = util.crc16_false(CrcContent);
				if (array[5] === crc16[0] && array[6] === crc16[1]) {
					console.log('电量：' + array[4]);
				}
			} else if (array[0] === 0x68 && array[2] === 0x0f && array[3] === 0x00 && array[14] === 0x16) {
				//阻抗数据
			} else if (array[0] === 0x68 && array[2] === 0x08 && array[3] === 0x07 && array[7] === 0x16){
				// 是否佩戴数据
			} else {
				//血流报文
				that.mergepack(array);
			}
		},
		// 组合报文 血流部分
		mergepack(blood) {
			let that = this;
			blood.forEach(aBlood => {
				totaldata[that.bloodCount] = aBlood;
				if (that.bloodCount < that.maxsize - 1) {
					that.bloodCount++;
				}
			});
			if (that.bloodCount >= that.maxsize - 1) {
				console.log(' i  am  blood data...');
				/*
				 * 说明: 格式>> 68 [1][1] [1] [8400] [1][1] 16
				 *
				 */
				//至此，包组合完成
				let body0 = totaldata.slice(1, 8404);
				let crc16 = util.crc16_false(body0);
				if (totaldata[8404] === crc16[0] && totaldata[8405] === crc16[1]) {
					console.log('crc pass！');
					let decode_front = totaldata.slice(4, 8404);
					let decode_later = util.Data_Decrypt(decode_front, decode_front.length);
					//得到解密后的血流报文（1000字节）
					if (totaldata[3] === 0x01) {
						//左脑血流
						console.log('左脑血流。。。。。。。。。。。。。。。。。。。。。。。' + bloodL.length);
						for (let i = 0; i < 2100; i++) {
							let BdataL = decode_later.slice(i * 4, i * 4 + 4).reverse();
							bloodL.push(util.convertFloat(BdataL));
						}
						console.log('血流数据LLL：：：' + bloodL.length+"====>>>"+bloodL);
					} else if (totaldata[3] === 0x02) {
						//右脑血流
						console.log('右脑血流。。。。。。。。。。。。。。。。。。。。。。。' + bloodR.length);
						for (let i = 0; i < 2100; i++) {
							let BdataR = decode_later.slice(i * 4, i * 4 + 4).reverse();
							bloodR.push(util.convertFloat(BdataR));
						}
						// console.log('血流数据RRR：：：' + bloodR.length+"====>>>"+bloodR);
						console.log('进度' + this.percent);
					} else {
						console.error('未知值');
					}
					if (bloodL.length === 2100 && bloodR.length === 2100) {
						console.log('模型数据足够：' + bloodL.length + 'RR::' + bloodR.length);
						that.SendMsg2Server();
					}
				}
				//。。。。
				that.bloodCount = 0;
				totaldata = new Array();
			}
		},
		//检查波形质量
		checkWave(wave) {
			let that = this;
			let userId = this.$store.state.userInfo.currentUser.userId;
			let data = {
				userId: userId,
				action: 'checkWave',
				params: {
					wave,
					frequency: 50
				}
			};
			api.checkWave(data).then(function(res) {
				console.log('checkWave success', res);
				let waveQuality = res.data.data.waveQuality
				if (waveQuality < 0.1) {
					that.$toast('数据不稳定,请务必保持静止的姿势')
					that.unStableCount++
				} else if (waveQuality < 0.4) {
					that.$toast('请保持安静继续检测')
				}
				if (that.unStableCount >= 2) {
					//..... 考虑中断检测
					that.reCheck()
				}
			}).catch(function(error) {
				console.log('checkWave fail', error);
			});
		},
		// 发送消息给服务器
		SendMsg2Server() {
			let that = this;
			let userId = this.$store.state.userInfo.currentUser.userId;
			let leftWave = bloodL;
			let rightWave = bloodR;
			if(that.overlayCount == 1) {
				leftWave = that.overlayData.L.concat(bloodL);
				rightWave = that.overlayData.R.concat(bloodR);
			}
			let data = {
				userId: userId,
				action: 'createUserModel',
				params: {
					left: leftWave,
					right: rightWave
				}
			};
			api.createUserModel(data).then(function(res) {
				console.log('createUserModel success', res);
				that.percent = 100;
				that.percentText = 100;
				/* 2001:{message:"数据异常,检查头环连接" --调整头环，重新开始
						 message:"数据不稳定,继续保持安静" -- 重新开始
						} 
					2000: message:建模成功
				 */
				// that.$refs.popup.open('center');
				if(res.data.code == 2001){ 
					clearTimeout(that.exceptionT);
					that.overlayCount = 0;
					if(res.data.message == "数据异常,检查头环连接") {
						let content={
							text1:"请您调整头环",
							text2:"保持安静",
							text3:"重新开始建模",
							btn_text:"再次建模"
						};
						that.icon_src = "../../../static/image/iconPopup/icon_quiet.png";
						that.$refs.annoyPopup.openPopup(content,'center');
						that.playAudio(that.$config.StaticUrl + "/audio/healthyModel/ajustBuild.mp3");
					}else if(res.data.message == "数据不稳定,继续保持安静") {
						// 叠加
						if(that.overlayCount == 0) {
							that.overlayCount++;
							that.overlayData.L = bloodL;
							that.overlayData.R = bloodR;
						}else{
							that.overlayCount = 0;
							that.overlayData = new Object();
						}
						let content={
							text1:"请您保持安静",
							text2:"为保证建模完整有效",
							text3:"即将重新开始建模",
							btn_text:"确定"
						};
						that.icon_src = "../../../static/image/iconPopup/icon_quiet.png";
						that.$refs.annoyPopup.openPopup(content,'center');
						that.playAudio(that.$config.StaticUrl + "/audio/healthyModel/reBuild.mp3");
					}
				}else if(res.data.code == 2000) {
					that.isOver = true;
					that.$store.commit('isBuildModel',true)
					if(that.whereGo) {
						console.log('2000');
						that.playAudio(that.$config.StaticUrl + "/audio/healthyModel/finshBuildModel.mp3");
						let t = setTimeout(()=>{
							clearTimeout(t)
							that.buildFinish()
							that.toFast()
						},4500)
					}else {
						console.log('3000');
						that.buildFinish()
						that.toDeep()
					}
				}
				// clear
				bloodL = new Array();
				bloodR = new Array();
			})
			.catch(function(error) {
				console.log('createUserModel fail', error);
			});
		},
		playAudio(src){
			this.innerAudioContext.src = src;
			this.innerAudioContext.play();
		},
		btnEvent(e){
			console.log('btnEvent >',e);
			this.$refs.annoyPopup.closePopup();
			switch (e){
				case "再次建模":
					this.reBuild();
					break;
				case "确定":
					this.reBuild();
					break;
				case "我知道了":
					this.buildFinish()
					this.toFast()
					break;
			}
		},
		/* 建模失败，重新开始
		 * 清理进度文字  移除监听器
		 * 关闭 弹出层 重新开始建模
		 */
		reBuild(){
			uni.$off('originalData');
			clearInterval(this.Timer);
			this.percent = 0//进度
			this.percentText=0, //进度文字
			this.StartBuild();
		},
		toFast(){
			// 跳转到快速检测
			uni.redirectTo({
				url:'/pages/detection/fastMonitor/fastMonitor?isFromBuildModel=' + true 
			})
		},
		toDeep(){
			app.writeBLEState(2);
			uni.redirectTo({
				url:'/pages/detection/deepMonitor/deepMonitor'
			})
		},
		toDetection(){
			app.writeBLEState(2);
			uni.switchTab({
				url:'/pages/detection/detection'
			})
		},
		buildFinish() {
			clearTimeout(this.delayTimer)
			clearInterval(this.Timer)
			// 销毁音乐实例
			this.innerAudioContext.destroy();
			bloodL = new Array();
			bloodR = new Array();
			totaldata = new Array();
		},
		// 监听返回按钮的触发
		onBackPress(options) {
			let that = this;
			that.exitCount++;
			if(that.exitCount >= 2) {
				that.buildFinish()
				that.toDetection()
			} 
			// 做一个返回判断 在规定时间内触发两次才可以
			let exitTimer = setTimeout(() =>{
				that.exitCount = 0;
				clearTimeout(exitTimer);
			},1000)
			this.$toast('再按一次退出建模')
			return true;
		}
	}
};
</script>

<style>
page {
	background-color: #ffffff;
}

>>> .uni-progress-bar {
	border-radius: 10px;
}

>>> .uni-progress-inner-bar {
	border-radius: 10px;
}
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
.content_bg {
	width: 100vw;
	height: 100vh;
	background-image: url('../../../static/gif/healthyScan.gif');
	background-size: 100% 100%;
}
.content1 {
	display: flex;
	flex-direction: column;
	align-items: center;
	width: 100vw;
	height: 100vh;
	background-color: #ffffff;
}
.icon_back {
	position: absolute;
	top: 80rpx;
	left: 32rpx;
	width: 113rpx;
	height: 38rpx;
}
.van-nav-bar {
	width: 750rpx;
	height: var(--status-bar-height);
	background-color: #007aff;
}
/*start 按钮 */
.outView {
	margin-top: 305rpx;
	width: 480rpx;
	height: 480rpx;
	background-color: #f4f4f4;
	border-radius: 50%;
}

.inView {
	width: 400rpx;
	height: 400rpx;
	background-color: #ffffff;
	border-radius: 50%;
}

.inView:active {
	background-color: #dcdcdc;
}
.flex-c {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.T1 {
	font-size: 100rpx;
	font-family: Source Han Sans SC;
	font-weight: 500;
	color: #0659c7;
}

.T2 {
	margin-top: 24rpx;
	font-size: 32rpx;
	font-family: Source Han Sans SC;
	font-weight: 600;
	color: #0659c7;
}

.Des {
	margin-top: 90rpx;
	font-size: 36rpx;
	font-family: Source Han Sans SC;
	font-weight: 400;
	color: #333333;
}

.popup1 {
	width: 620rpx;
	height: 750rpx;
	background-color: white;
	border-radius: 15px;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: space-between;
}

.icon_content {
	margin-top: 93rpx;
	width: 238rpx;
	height: 238rpx;
}
.popup1Content {
	margin-top: 20rpx;
	font-size: 52rpx;
	font-family: Source Han Sans CN;
	font-weight: normal;
	color: #333333;
}
.icon_close {
	width: 40rpx;
	height: 40rpx;
	position: absolute;
	top: 26rpx;
	right: 35rpx;
}
.popupBottomView {
	margin-bottom: 0rpx;
	width: 100%;
	height: 120rpx;
	border-radius: 0 0 15px 15px;
	background-color: #0659c7;
}
.popupBottomView text {
	font-size: 44rpx;
	font-family: Source Han Sans CN;
	font-weight: normal;
	color: #ffffff;
}

.head {
	width: 700rpx;
	height: 665rpx;
	/* background-color: #FFFFFF; */
	border-radius: 15px;
	display: flex;
	flex-direction: column;
	align-items: center;
}
.headT1 {
	margin-top: 73rpx;
	font-size: 54rpx;
	font-family: HYZongYiJ;
	font-weight: bold;
	color: #2ac2db;
	text-shadow: 0px 1px 1px rgba(0, 0, 0, 0.2);

	background: linear-gradient(0deg, #7ce9ff 46.728515625%, #deefff 100%);
	-webkit-background-clip: text;
	-webkit-text-fill-color: transparent;
}
.headT2 {
	margin-top: 35rpx;
	font-size: 32rpx;
	font-family: Source Han Sans SC;
	font-weight: normal;
	color: #999999;
}
.gifView {
	margin-top: 90rpx;
	width: 400rpx;
	height: 366rpx;
	position: relative;
}
.gifView image {
	height: 100%;
	position: absolute;
	width: 100%;
	left: 0px;
	top: 0px;
}
.perView {
	width: 500rpx;
	margin-top: 162rpx;
	display: flex;
	flex-direction: column;
	/* align-items: center; */
	justify-content: center;
}
.percentText {
	margin: auto auto 25rpx;
	font-size: 38rpx;
	font-family: Source Han Sans CN;
	font-weight: bold;
	color: #2ac2db;
}
.destext {
	font-size: 32rpx;
	font-family: Source Han Sans SC;
	font-weight: normal;
	color: #2ac2db;
}
</style>
